const app = getApp()
const request = require('../../../utils/request.js');
Page({
  data: {
    id: '',
    name: '',
    price: '',
    unit: '',
    image: '',
    stock: 0,
    quantity: 1,
    receiverName: '',
    receiverPhone: '',
    region: [],
    detailAddress: '',
    remark: '',
    freight: 0,
    totalAmount: 0,
    actualAmount: 0,
    residue: {}
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.loadGoodsDetail()
    }
  },

  // 加载商品详情
  loadGoodsDetail() {
    wx.showLoading({
      title: '加载中...'
    })

    request.request({
      url: `${app.globalData.baseUrl}/api/residues/${this.data.id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        const data = res.data.data
        this.setData({
          residue: data,
          name: data.name,
          price: data.price,
          unit: data.unit,
          image: app.globalData.baseUrl + data.image,
          stock: data.quantity
        })
        this.calculateAmount()
      },
      fail: (err) => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        console.error('加载商品详情失败:', err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 减少数量
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      })
      this.calculateAmount()
    }
  },

  // 增加数量
  increaseQuantity() {
    if (this.data.quantity < this.data.stock) {
      this.setData({
        quantity: this.data.quantity + 1
      })
      this.calculateAmount()
    } else {
      wx.showToast({
        title: '库存不足',
        icon: 'none'
      })
    }
  },

  // 数量输入
  onQuantityInput(e) {
    const value = parseInt(e.detail.value)
    if (value > 0 && value <= this.data.stock) {
      this.setData({
        quantity: value
      })
      this.calculateAmount()
    }
  },

  // 收货人输入
  onNameInput(e) {
    this.setData({
      receiverName: e.detail.value
    })
  },

  // 联系电话输入
  onPhoneInput(e) {
    this.setData({
      receiverPhone: e.detail.value
    })
  },

  // 地区选择
  onRegionChange(e) {
    this.setData({
      region: e.detail.value
    })
  },

  // 详细地址输入
  onAddressInput(e) {
    this.setData({
      detailAddress: e.detail.value
    })
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  // 计算金额
  calculateAmount() {
    const totalAmount = this.data.price * this.data.quantity
    const actualAmount = totalAmount + this.data.freight
    this.setData({
      totalAmount: totalAmount.toFixed(2),
      actualAmount: actualAmount.toFixed(2)
    })
  },

  // 验证表单
  validateForm() {
    if (!this.data.receiverName) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      })
      return false
    }

    if (!this.data.receiverPhone) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return false
    }

    if (!this.data.region.length) {
      wx.showToast({
        title: '请选择收货地区',
        icon: 'none'
      })
      return false
    }

    if (!this.data.detailAddress) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return false
    }

    return true
  },

  // 提交订单
  submitOrder() {
    if (!this.validateForm()) return

    wx.showLoading({
      title: '提交中...'
    })

    const orderData = {
      residue: this.data.residue,
      quantity: this.data.quantity,
      receiverName: this.data.receiverName,
      receiverPhone: this.data.receiverPhone,
      region: this.data.region.join("/"),
      detailAddress: this.data.detailAddress,
      remark: this.data.remark,
      totalAmount: this.data.totalAmount,
      freight: this.data.freight,
      actualAmount: this.data.actualAmount
    }

    request.request({
      url: `${app.globalData.baseUrl}/api/orders`,
      method: 'POST',
      data: orderData,
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        wx.hideLoading()
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        })
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/orders/detail/detail?id=${res.data.data.id}`
          })
        }, 1500)
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showToast({
          title: '提交失败',
          icon: 'none'
        })
        console.error('提交订单失败:', err)
      }
    })
  }
}) 